package com.pdx;

import org.apache.shiro.SecurityUtils;
import org.apache.shiro.authc.UsernamePasswordToken;
import org.apache.shiro.authz.AuthorizationException;
import org.apache.shiro.config.IniSecurityManagerFactory;
import org.apache.shiro.mgt.SecurityManager;
import org.apache.shiro.subject.Subject;
import org.apache.shiro.util.Factory;
import org.junit.Test;

/**
 * @author 派 大 星
 * @function
 * @date 2022/4/6 21:19
 * @website https://blog.csdn.net/Gaowumao
 */
public class HelloShiro {

    @Test
    public void shiroTest(){
        Subject subject = shiroLogin("jay","123");
        //判断用户是否已经登陆
        System.out.println("是否登陆成功："+subject.isAuthenticated());

        //-----------------检测当前用户的角色信息----------------------
        System.out.println("是否有管理员角色"+subject.hasRole("admin"));
        //-----------------如果当前用户有此角色，无返回值，若没有此权限，则抛出异常--------------
        try {
            subject.checkRole("coder");
            System.out.println("有coder角色");
        } catch (AuthorizationException e) {
            System.out.println("没有coder角色");
        }

        //---------------检查当前用户的权限信息------------------
        System.out.println("是否有查看订单列表的资源"+subject.isPermitted("order:list"));
        //---------------如果当前用户有此权限，无返回值，若没有此权限，则抛出异常------------------------------------
        try {
            subject.checkPermissions("order:add","order:del");
            System.out.println("有添加和删除订单的资源");
        } catch (AuthorizationException e) {
            System.out.println("没有添加和删除订单的权限");
        }


    }

    private Subject shiroLogin(String loginName,String password){
        Factory<SecurityManager> factory = new IniSecurityManagerFactory("classpath:shiro.ini");
        SecurityManager instance = factory.getInstance();
        SecurityUtils.setSecurityManager(instance);
        Subject subject = SecurityUtils.getSubject();
        UsernamePasswordToken token = new UsernamePasswordToken(loginName,password);
        subject.login(token);
        return subject;
    }
}
